import axios from "axios";
import LocalUtil from "@/utils/LocalUtil.ts";

const REQ = axios.create({
    headers: {
        "Content-Type": "application/json"
    }
})

export interface ResData<T> {
    msg: string,
    success: boolean,
    data: T
}

REQ.interceptors.request.use((instance) => {
    instance.headers.Authorization = LocalUtil.getToken()
    return instance
}, (config) => {
    console.error(config)
    window.messageApi.error("服务器错误，请联系网站管理员，稍后重试").then()
})

REQ.interceptors.response.use((instance) => {
    if (instance.data.success) {
        return instance.data
    } else {
        console.error(instance)
        window.messageApi.error(instance.data.msg).then()
        return Promise.reject()
    }
}, (config) => {
    console.error(config)
    if (config.response.data != null) {
        window.messageApi.error(config.response.data.msg).then()
    } else {
        window.messageApi.error("服务器错误，请联系网站管理员，稍后重试").then()
    }
    return Promise.reject()
})

export default REQ